package com.ruoyi.common.utils;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.sql.SqlUtil;

import java.util.List;

/**
 * 分页工具类
 * 
 * @author 最爱喝兽奶
 */
public class PageUtils extends PageHelper
{
    /**
     * 设置请求分页数据
     */
    public static void startPage()
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
        Boolean reasonable = pageDomain.getReasonable();
        PageHelper.startPage(pageNum, pageSize, orderBy).setReasonable(reasonable);
    }

    /**
     * 清理分页的线程变量
     */
    public static void clearPage()
    {
        PageHelper.clearPage();
    }

    public static <T> Page<T> buildPage(BaseEntity bo) {
        String pageSize = "10";
        String pageNum = "1";
        if (null != bo) {
            pageSize = bo.getPageSize() != null? bo.getPageSize(): "10";
            pageNum = bo.getPageNum() != null? bo.getPageNum(): "1";
        }
        return new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
    }

    public static <T> TableDataInfo buildTableDataInfo(Page<T> page) {
        TableDataInfo<T> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());
        tableDataInfo.setCode(200);
        return tableDataInfo;
    }

    public static <E> Page<E> convert(Page<?> src, List<E> list) {
        Page<E> target = new Page<>();
        BeanUtils.copyProperties(src, target);
        target.setRecords(list);
        return target;
    }
}
